---@module peripherals
--- 模块功能：按键驱动
-- @author openLuat
-- @module gpio.testGpioSingle
-- @license MIT
-- @copyright openLuat
-- @release 2018.03.27
module(..., package.seeall)
require "pins"
require "config"
pmd.ldoset(15, pmd.LDO_VMMC)
--[[
有些GPIO需要打开对应的ldo电压域才能正常工作，电压域和对应的GPIO关系如下
pmd.ldoset(x,pmd.LDO_VSIM1) -- GPIO 29、30、31

pmd.ldoset(x,pmd.LDO_VLCD) -- GPIO 0、1、2、3、4
--注意：
--Air724 A11以及之前的开发板丝印有误:
--丝印中的IO_0、IO_1、IO_2、IO_3、IO_4并不对应GPIO0、1、2、3、4
--丝印中的LCD_DIO、LCD_RS、LCD_CLK、LCD_CS对应GPIO0、1、2、3；模块的LCD_SEL引脚对应GPIO4


pmd.ldoset(x,pmd.LDO_VMMC) -- GPIO 24、25、26、27、28
x=0时：关闭LDO
x=1时：LDO输出1.716V
x=2时：LDO输出1.828V
x=3时：LDO输出1.939V
x=4时：LDO输出2.051V
x=5时：LDO输出2.162V
x=6时：LDO输出2.271V
x=7时：LDO输出2.375V
x=8时：LDO输出2.493V
x=9时：LDO输出2.607V
x=10时：LDO输出2.719V
x=11时：LDO输出2.831V
x=12时：LDO输出2.942V
x=13时：LDO输出3.054V
x=14时：LDO输出3.165V
x=15时：LDO输出3.177V
]]

-- 记录上次上升沿的时间
local BTN_ENTRY_NEGEDGE = -1
local BTN_RETURN_NEGEDGE = -1
local BTN_DOWN_NEGEDGE = -1

-----------------------------------3个按键注册函数-----------------------------------
local function KeyReturnFnc(msg)
    if msg == cpu.INT_GPIO_NEGEDGE then
        BTN_RETURN_NEGEDGE = rtos.tick() -- ticks，时间计数，每 tick 时长5ms
    elseif msg == cpu.INT_GPIO_POSEDGE then
        local curtick = rtos.tick()
        if curtick - BTN_RETURN_NEGEDGE > 400 then
            log.info("return key is long press")
            sys.publish("KEY_EVEN", "return_long")
        else
            log.info("return key is short press")
            sys.publish("KEY_EVEN", "return")
        end
        BTN_DOWN_NEGEDGE = -1
    end
end

local function KeyDownFnc(msg)
    if msg == cpu.INT_GPIO_NEGEDGE then
        BTN_DOWN_NEGEDGE = rtos.tick() -- ticks，时间计数，每 tick 时长5ms
    elseif msg == cpu.INT_GPIO_POSEDGE then
        local curtick = rtos.tick()
        if curtick - BTN_DOWN_NEGEDGE > 400 then
            log.info("down key is long press")
            sys.publish("KEY_EVEN", "down_long")
        else
            log.info("down key is short press")
            sys.publish("KEY_EVEN", "down")
        end
        BTN_DOWN_NEGEDGE = -1
    end
end

local function KeyEnterFnc(msg)
    if msg == cpu.INT_GPIO_NEGEDGE then
        BTN_ENTRY_NEGEDGE = rtos.tick() -- ticks，时间计数，每 tick 时长5ms
    elseif msg == cpu.INT_GPIO_POSEDGE then
        local curtick = rtos.tick()
        if curtick - BTN_ENTRY_NEGEDGE > 400 then
            log.info("enter key is long press")
            sys.publish("KEY_EVEN", "enter_long")
        else
            log.info("enter key is short press")
            sys.publish("KEY_EVEN", "enter")
        end
        BTN_ENTRY_NEGEDGE = -1
    end
end

sys.taskInit(function()
    local getKeyEnterFnc = pins.setup(pio.P0_11, KeyDownFnc, pio.PULLUP)
    sys.wait(1000)
    local getKeyUpFnc = pins.setup(pio.P0_10, KeyEnterFnc, pio.PULLUP)
    sys.wait(1000)
    local getKeyDownFnc = pins.setup(pio.P0_12, KeyReturnFnc, pio.PULLUP)
end)
